package br.ufc.customJDBC.routing;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import br.ufc.customJDBC.CustomConnection;
import br.ufc.customJDBC.csv.CSVLog;
import br.ufc.util.WrapperResultSet;

public class BroadcastRouter implements Router {

	private List<CustomConnection> connectionPool;
	private CSVLog csv;

	public BroadcastRouter(List<CustomConnection> connectionPool, CSVLog csv){
		this.connectionPool = connectionPool;
		this.csv = csv;
	}

	@Override
	public boolean execute(String sql) {
		return false;
	}

	@Override
	public ResultSet executeQuery(String sql) throws SQLException {

		List<ResultSet> resultSets = new ArrayList<ResultSet>(); 
		List<ExecuteQueryThread> threadPool = new ArrayList<ExecuteQueryThread >();
		List<CustomConnection> connections = this.connectionPool;

		long startTime = System.nanoTime();
		for(CustomConnection cc : connections){
			//			System.out.println(cc);
			ExecuteQueryThread thread = new ExecuteQueryThread(sql, cc);
			threadPool.add(thread);
			//			thread.setUncaughtExceptionHandler(h);
			thread.start();			
		}
		try {
			for(ExecuteQueryThread thread : threadPool){
				thread.join();
				resultSets.add(thread.getReturn());					
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		long stopTime = System.nanoTime();
		String nodes = "[";
		for(CustomConnection con : connections){
			nodes += con.getIp() + " ";
		}
		nodes += "]";

		csv.writeLine(sql, (stopTime - startTime), 1 , "MultiExecuteQuery", nodes );

		return WrapperResultSet.createResultSets(resultSets);
	}

	@Override
	public int executeUpdate(String sql) throws SQLException {
		return 0;
	}
}

